package com.iemes.controller.metals;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.AuditLoggingFormMap;
import com.iemes.entity.DepartmentForMap;
import com.iemes.entity.MetalsBomFormMap;
import com.iemes.entity.PartsReturnFormMap;
import com.iemes.entity.PurchaseRequestFormMap;
import com.iemes.entity.PurchaseSesaleStockFromMap;
import com.iemes.entity.SuppFilleFromMap;
import com.iemes.entity.UserFormMap;
import com.iemes.mapper.DepartmentMapper;
import com.iemes.mapper.SuppfilleMapper;
import com.iemes.mapper.UserMapper;
import com.iemes.mapper.metals.AuditLoggingMapper;
import com.iemes.mapper.metals.DeliverynoteMapper;
import com.iemes.mapper.metals.MetalsBomMapper;
import com.iemes.mapper.metals.PartsReturnMapper;
import com.iemes.mapper.metals.PurchaseRequestMapper;
import com.iemes.mapper.metals.PurchaseSaleStockMapper;
import com.iemes.plugin.PageView;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
@RequestMapping("/purchase")
@Controller
public class PurchaseRequestController extends BaseController {

	@Inject
	private PurchaseRequestMapper purchaseRequestMapper;
	
	@Inject DepartmentMapper departmentMapper;
	
	@Inject
	private UserMapper userMapper;
	
	@Inject
	private AuditLoggingMapper auditLoggingMapper;
	
	@Inject
	private PurchaseSaleStockMapper saleStockMapper;

	@Inject
	private MetalsBomMapper metalsBomMapper;
	
	@Inject
	private DeliverynoteMapper deliverynoteMapper;
	
	@Inject
	private PartsReturnMapper partsReturnMapper;
	
	@Inject
	private SuppfilleMapper suppfilleMapper;
	
	@RequestMapping("purchaseSaleStock")
	public String purchaseSaleStock(Model model){
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_sesaleStock_list";
	}
	
	private List<PurchaseSesaleStockFromMap> saleStockMapper(PurchaseSesaleStockFromMap sesaleStockFromMap) {
		// TODO Auto-generated method stub
		return null;
	}

	@RequestMapping("purchaseRequest")
	public String purchaseRequest(Model model){
		List<DepartmentForMap> departmentForMap=departmentMapper.findByWhere(new DepartmentForMap());
		List<SuppFilleFromMap> suppFilleFromMaps=purchaseRequestMapper.getsupplierfille();
		model.addAttribute("suppfille", suppFilleFromMaps);
		model.addAttribute("department", departmentForMap);
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_request_add";
	}
	
	
	
	/*	采购统计列表*/
	@RequestMapping("purchaseRequest-count")
	public String purchaseRequest_count(Model model){
		List<PurchaseRequestFormMap> purchaseRequestFormMap=purchaseRequestMapper.findByWhere(new PurchaseRequestFormMap());
		model.addAttribute("purchaseRequest", purchaseRequestFormMap);
		
		List<DepartmentForMap> departmentForMap=departmentMapper.findByWhere(new DepartmentForMap());
		model.addAttribute("departmentForMap",departmentForMap);
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_statistics_list";
	}
	

	

	
	/*采购情况列表*/
	@RequestMapping("purchaseRequest-details")
	public String metalsBom(Model model){
		List<PurchaseRequestFormMap> purchaseRequestFormMap=purchaseRequestMapper.findByWhere(new PurchaseRequestFormMap());
		model.addAttribute("purchaseRequest", purchaseRequestFormMap);
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_details_list";
	}
	
	
	@ResponseBody
	@RequestMapping("purchaseRequest_findByPageDetails")
	public PageView findByPageDetails(String pageNow, String pageSize) 
	{
		PurchaseRequestFormMap purchaseRequestFormMap = getFormMap(PurchaseRequestFormMap.class);//group by name
		purchaseRequestFormMap.put("state", 0);
		purchaseRequestFormMap.put("where", "group by buyId");
		purchaseRequestFormMap=toFormMap(purchaseRequestFormMap, pageNow, pageSize,purchaseRequestFormMap.getStr("orderby"));
		List<PurchaseRequestFormMap> purchaseRequestFormMaps = purchaseRequestMapper.findByPage(purchaseRequestFormMap);
		List<UserFormMap> userFormMaps = userMapper.findByWhere(new UserFormMap()); 
		List<AuditLoggingFormMap> auditLoggingFormMaps = auditLoggingMapper.findByWhere(new AuditLoggingFormMap());
		
		for(int i=0;i<purchaseRequestFormMaps.size();i++) {
			for(int j=0;j<userFormMaps.size();j++) {
				if(purchaseRequestFormMaps.get(i).get("userId").equals(userFormMaps.get(j).get("id"))) {
					purchaseRequestFormMaps.get(i).set("userId", userFormMaps.get(j).get("userName"));
				}	
			}
		}
		
		for(int i=0;i<purchaseRequestFormMaps.size();i++) {
			for(int j=0;j<auditLoggingFormMaps.size();j++) {
				if(auditLoggingFormMaps.get(j).getInt("auditCategoryId")==0) {
					if(purchaseRequestFormMaps.get(i).get("id").equals(auditLoggingFormMaps.get(j).get("auditId"))) {
						if(purchaseRequestFormMaps.get(i).getInt("state")==0){
							auditLoggingFormMaps.get(j).set("state", "待审核");
						}else if(purchaseRequestFormMaps.get(i).getInt("state")==1){
							auditLoggingFormMaps.get(j).set("state", "审核通过");
						}else if(purchaseRequestFormMaps.get(i).getInt("state")==2){
							auditLoggingFormMaps.get(j).set("state", "未通过");
						}
					}
				}
			}
		}
		
//		LuogicPaging(pageNow, pageSize, purchaseRequestFormMaps);
		pageView.setRecords(purchaseRequestFormMaps);
		return pageView;
	}
	
	
	@ResponseBody
	@RequestMapping("purchaseRequest_findByPage")
	public PageView findByPage(String pageNow, String pageSize) 
	{
		PurchaseRequestFormMap purchaseRequestFormMap = getFormMap(PurchaseRequestFormMap.class);
		PartsReturnFormMap partsReturnFormMap = new PartsReturnFormMap();
		purchaseRequestFormMap.put("state", 0);
		purchaseRequestFormMap.put("orderby", "group by buyId");
		partsReturnFormMap.put("where", "where state=0");
		purchaseRequestFormMap=toFormMap(purchaseRequestFormMap, pageNow, pageSize,purchaseRequestFormMap.getStr("orderby"));
		List<PurchaseRequestFormMap> purchaseRequestFormMaps = purchaseRequestMapper.findByPage(purchaseRequestFormMap);		
		List<DepartmentForMap> departmentForMaps = departmentMapper.findByWhere(new DepartmentForMap());
		
		for (PurchaseRequestFormMap pur : purchaseRequestFormMaps) {
			for (DepartmentForMap dep : departmentForMaps) {
				if(pur.get("departmentId").toString().equals(dep.get("id").toString())) {
					pur.set("departmentId",dep.get("name"));		
				}
			}
		}
		
		
		for (int i=0;i<purchaseRequestFormMaps.size();i++) {
			if(purchaseRequestFormMaps.get(i).getInt("flow")==0) {
				List<PurchaseRequestFormMap> purRoutine1 = purchaseRequestMapper.getAcceptanceRoutine(purchaseRequestFormMaps.get(i).getInt("id"));
				if(purRoutine1.size()!=0) {
					for(int j=0;j<purRoutine1.size();j++) {
						List<AuditLoggingFormMap> aud = purchaseRequestMapper.getAcceptanceRoutine2(purRoutine1.get(j).get("buyId").toString());
						if(aud.size()!=4) {
							purchaseRequestFormMaps.remove(i);
							i--;
						}
					}
				}else if(purRoutine1.size()==0){
					
					purchaseRequestFormMaps.remove(i);
					i--;
				}								
			}else {
				List<PurchaseRequestFormMap> purRoutine1 = purchaseRequestMapper.getAcceptanceSpecial(purchaseRequestFormMaps.get(i).getInt("id"));
				if(purRoutine1.size()!=0) {
					for(int j=0;j<purRoutine1.size();j++) {
						List<AuditLoggingFormMap> aud = purchaseRequestMapper.getAcceptanceSpecia2(purRoutine1.get(j).get("buyId").toString());
						int sum = purchaseRequestMapper.getAcceptanceSpeciaSUM(purRoutine1.get(0).getInt("buyId"));
						if(sum>=1000) {
							if(aud.size()!=6) {
								purchaseRequestFormMaps.remove(i);
								i--;
							}		
						}else if(aud.size()!=5 && sum<=1000) {
							purchaseRequestFormMaps.remove(i);
							i--;
						}
					}
				}else if(purRoutine1.size()==0){	
					purchaseRequestFormMaps.remove(i);
					i--;
				}
			}
		}
			
		
		pageView.setRecords(purchaseRequestFormMaps);
		return pageView;
	}

	
	
	
	
	
	@ResponseBody
	@RequestMapping("purchaseSaleStock_findByPage")
	public PageView saleStockfindByPage(String pageNow, String pageSize) 
	{
		PurchaseSesaleStockFromMap sesaleStockFromMap = getFormMap(PurchaseSesaleStockFromMap.class);
		MetalsBomFormMap metalsBomFormMap = new MetalsBomFormMap();
		metalsBomFormMap.put("where", "where state=0");
		sesaleStockFromMap.put("state", 0);
		sesaleStockFromMap=toFormMap(sesaleStockFromMap, pageNow, pageSize,sesaleStockFromMap.getStr("orderby"));
		List<PurchaseSesaleStockFromMap> sesaleStockFromMaps = saleStockMapper.findByPage(sesaleStockFromMap);
		List<MetalsBomFormMap> metalsBomFormMaps=metalsBomMapper.findByWhere(metalsBomFormMap);
		List<PurchaseRequestFormMap> purchaseRequestFormMap=purchaseRequestMapper.findByWhere(new PurchaseRequestFormMap());

		for(int i=0;i<sesaleStockFromMaps.size();i++) {
			for(int j=0;j<purchaseRequestFormMap.size();j++) {
				if(sesaleStockFromMaps.get(i).get("deliveryNoteId").equals(purchaseRequestFormMap.get(j).get("buyId"))) {
					sesaleStockFromMaps.get(i).put("materialCode", metalsBomFormMaps.get(j).get("materialCode"));
					sesaleStockFromMaps.get(i).put("name", metalsBomFormMaps.get(j).get("name"));
					sesaleStockFromMaps.get(i).put("specifications", metalsBomFormMaps.get(j).get("specifications"));
					sesaleStockFromMaps.get(i).put("unit", metalsBomFormMaps.get(j).get("unit"));
				}	
			}
		}

		pageView.setRecords(sesaleStockFromMaps);
		return pageView;
	}
	
	@ResponseBody
	@RequestMapping(value="purchaseRequest_deleteEntity")
	@SystemLog(module="采购统计",methods="采购-删除物料")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		
		PurchaseRequestFormMap purchaseRequestFormMap=getFormMap(PurchaseRequestFormMap.class);
		String[] ids = getParaValues("ids");
		String arr=ids[0];
		String[] str=arr.split(",");
		
		for(int i=0;i<str.length;i++){
			PurchaseRequestFormMap purchaseRequestFormMap1 =  purchaseRequestMapper.findbyFrist("id", ids[i], PurchaseRequestFormMap.class);
			String buyId = purchaseRequestFormMap1.get("buyId").toString();
			List<PurchaseRequestFormMap> purchaseRequestFormMaps = purchaseRequestMapper.findByAttribute("buyId", buyId, PurchaseRequestFormMap.class);
			int j = 2;
			
			for (PurchaseRequestFormMap pur : purchaseRequestFormMaps) {
				pur.set("state", j);
				purchaseRequestMapper.editEntity(pur);
			}				
		}	
		return "success";
	}
	
	
	
	/*修改物料*/
	@RequestMapping("purchaseRequest_edit")
	public String editUI(Model model) throws Exception 
	{
		String id = getPara("id");
		//获取物料对象				
		PurchaseRequestFormMap purchaseRequestFormMap = purchaseRequestMapper.findbyFrist("id", id, PurchaseRequestFormMap.class);		
		MetalsBomFormMap metalsBomFormMap = metalsBomMapper.findbyFrist("id",purchaseRequestFormMap.get("metalsBomId").toString(), MetalsBomFormMap.class);	
		model.addAttribute("metalsbom", metalsBomFormMap);
		model.addAttribute("purchaseRequest", purchaseRequestFormMap);
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_statistics_edit";
	}
	
	@ResponseBody
	@RequestMapping(value="purchaseRequest_editEntity")
	@SystemLog(module="五金采购清单",methods="采购-修改物料")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity() throws Exception {
		MetalsBomFormMap metalsBomFormMap = getFormMap(MetalsBomFormMap.class);
		PurchaseRequestFormMap purchaseRequestFormMap = getFormMap(PurchaseRequestFormMap.class);
		metalsBomMapper.editEntity(metalsBomFormMap);
		purchaseRequestMapper.editEntity(purchaseRequestFormMap);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value="metalsbom_choose")
	public MetalsBomFormMap emetalsbom_choose(String id) throws Exception {
		//获取物料对象		
		MetalsBomFormMap metalsBomFormMap = metalsBomMapper.findbyFrist("id", id, MetalsBomFormMap.class);			
		return metalsBomFormMap;
	}
	
	@ResponseBody
	@RequestMapping(value="metalsbom")
	public List<MetalsBomFormMap> metalsbom(String id) throws Exception {
		SuppFilleFromMap suppFilleFromMap = new SuppFilleFromMap();
		suppFilleFromMap.put("where", "where identity=1 and suppNumber="+id);
		List<SuppFilleFromMap> suppFilleFromMaps = suppfilleMapper.findByWhere(suppFilleFromMap);
		List<MetalsBomFormMap> metalsBomFormMaps = new ArrayList<MetalsBomFormMap>();
		for (SuppFilleFromMap sup : suppFilleFromMaps) {
			MetalsBomFormMap metalsBomFormMap = metalsBomMapper.findbyFrist("materialCode", sup.get("materialNo").toString(), MetalsBomFormMap.class);
			metalsBomFormMaps.add(metalsBomFormMap);
		}
		return metalsBomFormMaps;
	}
	

	@RequestMapping(value="purchase_metalsbom_details")
	public String purchase_metalsbom_details(Model model) throws Exception {
		//获取采购单号	
		String id = getPara("buyId");
		PurchaseRequestFormMap purchaseRequestFormMap =  purchaseRequestMapper.findbyFrist("id", id, PurchaseRequestFormMap.class);
		String buyId = purchaseRequestFormMap.get("buyId").toString();
		int auditCategoryId = 0;
		List<AuditLoggingFormMap> auditLoggingFormMaps=auditLoggingMapper.getAuditLoggingByAuditId(id,auditCategoryId);		
		List<MetalsBomFormMap> metalsBomFormMaps = new ArrayList<MetalsBomFormMap>();
		List<PurchaseRequestFormMap> PurchaseRequestFormMaps = purchaseRequestMapper.findByAttribute("buyId", buyId, PurchaseRequestFormMap.class);
		
		
		List<UserFormMap> userFormMap = userMapper.findByWhere(new UserFormMap());
		List<UserFormMap> userFormMaps = new ArrayList<UserFormMap>();
		List<DepartmentForMap> departmentForMaps=departmentMapper.findByWhere(new DepartmentForMap());
		List<SuppFilleFromMap> suppFilleFromMaps=purchaseRequestMapper.getsupplierfille();
		List supplierIds = new ArrayList();
		
		for(int i=0;i<departmentForMaps.size();i++) {
			if(purchaseRequestFormMap.get("departmentId").toString().equals(departmentForMaps.get(i).get("id").toString())) {
				purchaseRequestFormMap.set("departmentId", departmentForMaps.get(i).get("name").toString());
			}
		}
		
		for(int i=0;i<userFormMap.size();i++) {
			if(purchaseRequestFormMap.get("userId").toString().equals(userFormMap.get(i).get("id").toString())) {
				purchaseRequestFormMap.put("userName", userFormMap.get(i).get("userName"));
			}
		}
		
		for(int i=0;i<auditLoggingFormMaps.size();i++) {
			for(int j=0;j<userFormMap.size();j++) {
				if(auditLoggingFormMaps.get(i).get("userId").toString().equals(userFormMap.get(j).get("id").toString())) {
					userFormMap.get(j).put("auditTime", auditLoggingFormMaps.get(i).get("auditTime"));
					userFormMaps.add(i, userFormMap.get(j));
				}
			}		
		}
		
		if(purchaseRequestFormMap.get("flow").toString().equals("0")) {
			purchaseRequestFormMap.set("flow","常规流程");
		}else {
			purchaseRequestFormMap.set("flow","特殊流程");
		}
		
		for(int i=0;i<PurchaseRequestFormMaps.size();i++) {
			MetalsBomFormMap metalsBomFormMap = metalsBomMapper.findbyFrist("id", PurchaseRequestFormMaps.get(i).get("metalsBomId").toString(), MetalsBomFormMap.class);
			for(int j=0;j<suppFilleFromMaps.size();j++) {				
					if(suppFilleFromMaps.get(j).get("suppNumber").toString().equals(PurchaseRequestFormMaps.get(i).get("supplierId").toString())) {
						PurchaseRequestFormMaps.get(i).set("supplierId", suppFilleFromMaps.get(j).get("suppName").toString());						
					}
			}
			
			metalsBomFormMap.put("supplierId",PurchaseRequestFormMaps.get(i).get("supplierId").toString());
			metalsBomFormMap.put("number", PurchaseRequestFormMaps.get(i).get("number").toString());
			metalsBomFormMap.put("price", PurchaseRequestFormMaps.get(i).get("price").toString());
			metalsBomFormMap.put("total", PurchaseRequestFormMaps.get(i).get("total").toString());
			metalsBomFormMap.put("comment", PurchaseRequestFormMaps.get(i).get("comment").toString());
			metalsBomFormMaps.add(metalsBomFormMap);
		}
		
		model.addAttribute("purchaseRequest", purchaseRequestFormMap);
		model.addAttribute("metalsBom", metalsBomFormMaps);
		model.addAttribute("userFormMaps", userFormMaps);
		model.addAttribute("auditLogging", auditLoggingFormMaps);
		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_details";
	}
	
	
	
	
	
	
	
	@ResponseBody
	@RequestMapping("purchase_addrequest")
	@SystemLog(module="申请采购",methods="新增采购")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity() throws Exception {		
		// 获取request
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		UserFormMap userFormMap = (UserFormMap)Common.findUserSession(request);
		int auditCategoryId = 0;
		
		String[] suppNumber = request.getParameterValues("suppNumber");
		String[] flow = request.getParameterValues("flow");
		String[] departmentId = request.getParameterValues("departmentId");
		String[] buyId = request.getParameterValues("buyId");
		String[] bomid = request.getParameterValues("bomid");
		String[] name = request.getParameterValues("name");
		String[] specifications = request.getParameterValues("specifications");
		String[] unit = request.getParameterValues("unit");
		String[] number = request.getParameterValues("number");
		String[] price = request.getParameterValues("price");
		String[] total = request.getParameterValues("total");
		String[] inventoryTotal = request.getParameterValues("inventoryTotal");
		String[] comment = request.getParameterValues("comment");

		if(null != bomid) {
			for(int i=0;i<bomid.length;i++) {
				PurchaseRequestFormMap purchaseRequestFormMap=new PurchaseRequestFormMap();
				purchaseRequestFormMap.set("fillingDate", DateUtils.getStringDateTime());
				purchaseRequestFormMap.set("userId", userFormMap.getInt("id"));
				purchaseRequestFormMap.put("metalsBomId", bomid[i]);
				purchaseRequestFormMap.set("state", 0);
				purchaseRequestFormMap.set("number", number[i]);
				purchaseRequestFormMap.set("price", price[i]);
				purchaseRequestFormMap.set("total", total[i]);
				purchaseRequestFormMap.set("comment", comment[i]);
				purchaseRequestFormMap.set("flow", flow[0]);
				purchaseRequestFormMap.set("departmentId", departmentId[0]);
				purchaseRequestFormMap.set("buyId", buyId[0]);
				purchaseRequestFormMap.set("supplierId", suppNumber[i]);
				purchaseRequestMapper.addEntity(purchaseRequestFormMap);
				
//				try {		
//					List<PurchaseRequestFormMap> purchaseRequestFormMaps=purchaseRequestMapper.findByWhere(new PurchaseRequestFormMap());							
//					AuditLoggingFormMap auditLoggingFormMap = new AuditLoggingFormMap();
//					auditLoggingFormMap.set("auditCategoryId", auditCategoryId);
//					auditLoggingFormMap.set("auditCategoryId", purchaseRequestFormMaps.get(purchaseRequestFormMaps.size()-1).getInt("buyId"));
//					auditLoggingFormMap.set("state", 0);
//					auditLoggingFormMap.set("auditId", purchaseRequestFormMaps.get(purchaseRequestFormMaps.size()-1).getInt("id"));		
//					auditLoggingMapper.addEntity(auditLoggingFormMap);
//				} catch (Exception e) {
//					return "false";
//				}
			}
			return "success";
		}
		return "false";
	}
	
//	@RequestMapping("purchase_acceptanceOpinion")
//	public String addUI(Model model) throws Exception {
//		return Common.BACKGROUND_PATH + "/metals/purchase/purchase_acceptance";
//	}
	
	
	@RequestMapping("purchase_acceptance")
	@ResponseBody
	@SystemLog(module="申请采购",methods="验收采购")//凡需要处理业务逻辑的.都需要记录操作日志
	public String purchase_acceptance() throws Exception {
		String id = getPara("id");
		PurchaseRequestFormMap purchaseRequestFormMap =  purchaseRequestMapper.findbyFrist("id", id, PurchaseRequestFormMap.class);
		String buyId = purchaseRequestFormMap.get("buyId").toString();
		List<PurchaseRequestFormMap> purchaseRequestFormMaps = purchaseRequestMapper.findByAttribute("buyId", buyId, PurchaseRequestFormMap.class);
		int i = 2;
		
		for (PurchaseRequestFormMap pur : purchaseRequestFormMaps) {
			pur.set("state", i);
			purchaseRequestMapper.editEntity(pur);
		}
		
		return "success";
	}
	
	
	
	
}
